/**
 * @description:
 * @param {array} list 待处理数据
 * @param {string} [key= "id"] 键值
 * @param {boolean|function} [integrate= false] 是否整合([整合数据,数据首项])
 * @return {object|object[]}
 */
export function createHashTable(list = [], key = "id", integrate = false) {
  // 创建一个哈希表
  const hashTable = {};
  if (key === true || typeof key === "function") {
    integrate = key;
    key = "id";
  }
  if (integrate) {
    const getValue = (() => {
      if (typeof integrate === "function") return integrate;
      return item => item;
    })();
    const firstArray = [];
    const firstObject = {};
    //如果key或者integrate为true则开启整合
    for (const element of list) {
      const data = getValue(element);
      if (hashTable[element[key]]) {
        hashTable[element[key]].push(data);
      } else {
        firstArray.push(element);
        firstObject[element[key]] = data;
        hashTable[element[key]] = [data];
      }
    }
    return [hashTable, firstArray, firstObject];
  } else {
    for (const element of list) {
      hashTable[element[key]] = element;
    }
    return hashTable;
  }
}

//数据快照
export function dataSnapshot(data) {
  const snapshot = JSON.stringify(data);
  return changeData => snapshot === JSON.stringify(changeData);
}
